import a from 'axios'
import ls from 'store2'
const axios = a.create({	
	baseURL: '/mall-api' ,
	timeout: 30000
})

const getHeader = () => {
	let headers = {
		'content-type': 'application/json',
		'Access-Control-Allow-Origin': '*',
	}
	return headers
}
// 返回状态判断
axios.interceptors.request.use(function (config) { // 每次请求时会从localStorage中获取token
    let token = ls.get('tokensyxk') 
    if (token) {
        config.headers.common['Authorization'] ='Bearer '+token
	}
	return config
}, function (error) {
    return Promise.reject(error)
})
axios.interceptors.response.use((res) => {
	if (res.data.code == '200') {
		return res.data		
	} else  if(res.data.code == '401'){
		ls.remove('tokensyxk')
		let types;
		if(window.$nuxt.$route.name==='univ'){types='yxk'}else if(window.$nuxt.$route.name==='user'){types='users'}
		window.$nuxt.$router.replace('/login/msgLogin')	
	}
	return res
}, (error) => {
	return Promise.reject(error)
})

let loginLoading = false;
let loginPromise;
let methods = {
	put_http(url, params) {
		return axios({
			method: 'PUT',
			url,
			data: params,
			headers: getHeader()
		})
	},
	delete_http(url, params) {
		return axios({
			method: 'DELETE',
			url,
			data: params,
			headers: getHeader()
		})
	},
	post_http(url, params) {
		return axios({
			method: 'POST',
			url,
			data: params,
			headers: getHeader()
		})
	},
	postForm_http(url, params) {
		let headers = getHeader()
		headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
		return axios({
			method: 'POST',
			url,
			data: qs.stringify(params),
			headers
		})
	},
	get_http(url, params) {
		return axios({
			method: 'GET',
			url,
			params,
			headers: getHeader()
		})
	},
	put(url, params, requireLogin) {
		if (requireLogin && loginLoading) {
			return loginPromise.then(() => {
				return this.put_http(url, params)
			})
		} else {
			return this.put_http(url, params)
		}
	},
	get(url, params, requireLogin) {
		if (requireLogin && loginLoading) {
			return loginPromise.then(() => {
				return this.get_http(url, params)
			})
		} else {
			return this.get_http(url, params)
		}
	},
	post(url, params, requireLogin) {
		if (requireLogin && loginLoading) {
			return loginPromise.then(() => {
				return this.post_http(url, params)
			})
		} else {
			return this.post_http(url, params)
		}
	},
	login(code) {
		loginLoading = true;
		loginPromise = this.post('/login', {
			"code": code,
		}).then(res => {
			loginLoading = false;
			const {
				token,
				openId,
				sign
			} = res.data;
			ls.set('token', token);
			ls.set('sign', sign);
			ls.set('openId', openId);
			// this.userInfo();
		}).catch(err => {
			loginLoading = false;
			ls.set('token', null);
		});
	},
}
export default methods
